package com.luo.system.controller;

import com.luo.common.annotation.Log;
import com.luo.common.config.Constant;
import com.luo.common.controller.BaseController;
import com.luo.common.domain.Tree;
import com.luo.common.service.DictService;
import com.luo.common.utils.*;
import com.luo.partner.dao.model.TabDomain;
import com.luo.partner.service.TabDomainService;
import com.luo.partner.service.TabUsrsService;
import com.luo.system.domain.DeptDO;
import com.luo.system.domain.RoleDO;
import com.luo.system.domain.UserDO;
import com.luo.system.service.RoleService;
import com.luo.system.service.UserService;
import com.luo.system.vo.UserVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private String prefix = "system/user";
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    DictService dictService;
	
	@Autowired
	TabDomainService tabDomainService;

    @Value("${bootdo.qrcodecontent}")
    String qrcodecontent;

    @Value("${bootdo.uploadPath}")
    String uploadPath;

    @Value("${bootdo.qrcodeurl}")
    String qrcodeurl;

    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String, Object> params) {
        UserDO loginUser = getUser();
        //等级（0超级管理员，1合伙人管理员，2合伙人）
        if (loginUser.getLevel() == 1) {
            // 合伙人管理员登录的就可以看到他下面的所有合伙人
            params.put("superUserId", loginUser.getUserId());
        }
        // 查询列表数据
        Query query = new Query(params);
        List<UserDO> sysUserList = userService.list(query);
        int total = userService.count(query);
        PageUtils pageUtil = new PageUtils(sysUserList, total);
        return pageUtil;
    }

    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        UserDO loginUserDO = getUser();
        model.addAttribute("level", loginUserDO.getLevel());
        List<RoleDO> returnRoles = new ArrayList<RoleDO>();
        List<RoleDO> roles = roleService.list();
        if (roles != null && roles.size() > 0) {
            //等级（0超级管理员，1合伙人管理员，2合伙人）
            switch (loginUserDO.getLevel()) {
                case 0:
                    for (RoleDO roleDO : roles) {
                        if (!"合伙人".equals(roleDO.getRoleName())) {
                            returnRoles.add(roleDO);
                        }
                    }
                    break;
                case 1:
                    for (RoleDO roleDO : roles) {
                        if ("合伙人".equals(roleDO.getRoleName())) {
                            returnRoles.add(roleDO);
                        }
                    }
                    break;
                case 2:

                    break;

                default:
                    break;
            }
        }
        model.addAttribute("roles", returnRoles);
        return prefix + "/add";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDO crUserDO = getUser();
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        model.addAttribute("level", crUserDO.getLevel());
        List<RoleDO> roles = roleService.list(id);
        model.addAttribute("roles", roles);
        return prefix + "/edit";
    }

    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    R save(UserDO user) {
        UserDO cur = getUser();
        if (cur.getLevel() == 1) {
            user.setExtWebsite(cur.getExtWebsite());
        }

        user.setDeptId(6l);
        user.setEmail("");
        user.setUserIdCreate(getUser().getUserId());
        user.setGmtCreate(new Date());
        user.setGmtModified(new Date());
        user.setSex(0l);
        user.setBirth(new Date());
        user.setTotalCommission(new BigDecimal(0));
        user.setUnWithdrawCommission(new BigDecimal(0));
        user.setWithdrawCommission(new BigDecimal(0));
        user.setFreezeCommission(new BigDecimal(0));
        user.setSuperUserId(getUser().getUserId());
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        int userId = userService.save(user);
        if (userId > 0) {
            if (cur.getLevel() == 1) {
                // 生成二维码
                String content = qrcodecontent + userId;
                String fileName = QrCodeUtil.createQrcode(content, uploadPath, userId);
                user.setQrcodeurl(qrcodeurl + fileName);
                userService.update(user);
            }

            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    R update(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.update(user) > 0) {
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    R updatePeronal(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.updatePersonal(user) > 0) {
            UserDO cur = getUser();
            if (cur.getLevel() == 1) {
                // 修改他下面所有合伙人的推广网站
            }
            return R.ok();
        }
        return R.error();
    }


    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    R remove(Long id) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    R batchRemove(@RequestParam("ids[]") Long[] userIds) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        int r = userService.batchremove(userIds);
        if (r > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:updateQrcode")
    @Log("更新所有合伙人的二维码")
    @PostMapping("/updateQrcode")
    @ResponseBody
    R updateQrcode() {
        try {
            List<UserDO> list = userService.list(new HashMap<String, Object>());
            if (list != null) {
                for (UserDO userDO : list) {
                    if (userDO.getLevel() == 2) {
                        // 生成二维码
                        String content = qrcodecontent + userDO.getUserId();
                        String fileName = QrCodeUtil.createQrcode(content, uploadPath, userDO.getUserId());
                        if (fileName != null) {
                            userDO.setQrcodeurl(qrcodeurl + fileName);
                            userService.update(userDO);
                        } else {
                            logger.error("更新用户" + userDO.getUserId() + "的二维码失败");
                        }
                    }
                }
            }
        } catch (Exception e) {
            R.error("更新失败，" + e.getMessage());
        }

        return R.ok();
    }

    @PostMapping("/exit")
    @ResponseBody
    boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {

        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    R resetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.resetPwd(userVO, getUser());
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @Log("提交更改域名")
    @PostMapping("/resetDomain")
    @ResponseBody
    R resetDomain(TabDomain tabDomain) {
        try {
        	tabDomainService.update(tabDomain);
        	
            return R.ok(tabDomain.getDomainName());
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    R adminResetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.adminResetPwd(userVO);
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }

    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.get(getUserId());
        // 从数据库中找出域名
        TabDomain tabDomain = tabDomainService.get(null);
     	model.addAttribute("domain", tabDomain.getDomainName());
        model.addAttribute("user", userDO);
        model.addAttribute("hobbyList", dictService.getHobbyList(userDO));
        model.addAttribute("sexList", dictService.getSexList());
        return prefix + "/personal";
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        if ("test".equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        Map<String, Object> result = new HashMap<>();
        try {
            result = userService.updatePersonalImg(file, avatar_data, getUserId());
        } catch (Exception e) {
            return R.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error("更新图像失败！");
        }
    }

    @ResponseBody
    @RequestMapping("/downlist")
    public List<UserDO> downlist() {
        UserDO currUser = ShiroUtils.getUser();
        HashMap<String, Object> params = new HashMap<>();
        UserDO userDO = userService.get(currUser.getUserId());
        List<Long> roleIds = userDO.getRoleIds();

        List<UserDO> userDOList = new ArrayList<>();
        //如果用户不是超级管理员
        if (roleIds.contains(1L)) {
            return userService.list(params);
        }

        //是合伙人管理员
        if (roleIds.contains(59L)) {
            params.put("superUserId", currUser.getUserId());
            return userService.list(params);
        }
        userDOList.add(userDO);
        return userDOList;
    }
}
